package com.rem.elasticsearch.apidemo.doc;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

import static org.apache.http.HttpHost.DEFAULT_SCHEME_NAME;

/**
 * ；批量创建文档
 *
 * @author Rem
 * @date 2021-05-16
 */

@Slf4j
public class DocInsertBatch {


    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, DEFAULT_SCHEME_NAME)));

        // 批量插入数据
        BulkRequest request = new BulkRequest();


        request.add(new IndexRequest().index("user").id("2002").source(XContentType.JSON, "name", "wangwu", "age", 30, "sex", "女"));
        request.add(new IndexRequest().index("user").id("2003").source(XContentType.JSON, "name", "wangwu", "age", 40, "sex", "男"));
        request.add(new IndexRequest().index("user").id("2004").source(XContentType.JSON, "name", "wangwu1", "age", 40, "sex", "女"));
        request.add(new IndexRequest().index("user").id("2005").source(XContentType.JSON, "name", "wangwu2", "age", 50, "sex", "男"));
        request.add(new IndexRequest().index("user").id("2006").source(XContentType.JSON, "name", "wangwu3", "age", 50, "sex", "男"));
        request.add(new IndexRequest().index("user").id("2007").source(XContentType.JSON, "name", "wangwu44", "age", 60, "sex", "女"));
        request.add(new IndexRequest().index("user").id("2008").source(XContentType.JSON, "name", "wangwu555", "age", 60, "sex", "男"));
        request.add(new IndexRequest().index("user").id("2009").source(XContentType.JSON, "name", "wangwu66666", "age", 60, "sex", "男"));

        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.getTook());
        System.out.println(response.getItems());

        // 关闭ES客户端
        esClient.close();
    }
}
